﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBSourceToolsLib;
using Microsoft.SqlServer.Management;
using DBConnectionLib;

//set DB_BASE_DIR=..\..\
//set BASE_BIN_DIR=..\..\bin\
//set PROJECT_BASE_DIR=..\..\..\
//"%BASE_BIN_DIR%DBSourceDataLoader.exe" 
//%PROJECT_BASE_DIR% local_ITAMSDatabase_1.0.3 deploy_ITAMSDatabase_1.0.4 "Alesco_CLevels" "%DB_BASE_DIR%\xml\ITAMSDatabase_1.0.3.xml"
using StructureMap;

namespace DBSourceDataLoader
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ObjectFactory.Initialize(x => x.AddRegistry(new CommandLineRegistry()));

                string strDatabaseXmlDir = args[0];
                string strSourceDatabaseName = args[1];
                string strTargetDatabaseName = args[2];
                string strTableName = args[3];
                string strDatabasesFile = args[4];

                System.Console.WriteLine(" Load Xml dir  : " + strDatabaseXmlDir);
                System.Console.WriteLine(" Load Database : "+ strSourceDatabaseName);
                System.Console.WriteLine(" Load Target   : " + strTargetDatabaseName);
                

                string strFullyQualifiedTableName = "";
                string[] strTableNameArr = strTableName.Split('.');
                int iCountSplit = 0;
                foreach (string strTableNameSplit in strTableNameArr)
                {
                    if (iCountSplit > 0)
                        strFullyQualifiedTableName += ".";
                    strFullyQualifiedTableName += "[" + strTableNameSplit + "]";
                    iCountSplit++;
                }

                System.Console.WriteLine(" Load Table    : " + strFullyQualifiedTableName);


                DBSourceToolsLib.DatabaseProject oDBProject = new DatabaseProject(strDatabasesFile);
                oDBProject.LoadFromDisk(false);
                UserSettings.Instance().ProjectBaseDirectory = oDBProject.BaseDirectory;
                //UserSettings.Instance().LoadDatabasesEx(strDatabaseXmlDir, strDatabasesFile);

                DatabaseEx oSourceDatabase = oDBProject.GetDatabaseEx(strSourceDatabaseName);

                Database oTargetDatabase = oDBProject.GetDatabaseEx(strTargetDatabaseName);

                //sysObjects.LoadDeploymentTargets();
                if (oTargetDatabase == null)
                {
                    throw new Exception("Could not load Deployment Target " + strTargetDatabaseName);
                }
                string strTableXml = strDatabaseXmlDir + "\\" + strSourceDatabaseName + "\\Tables\\Data\\" + strTableName + ".xml";
                string strSchemaXml = strDatabaseXmlDir + "\\" + strSourceDatabaseName + "\\Tables\\Data\\" + strTableName + "_Schema.xml";

                if (!System.IO.File.Exists(strTableXml))
                {
                    throw new Exception("Could not load file : " + strTableXml);
                }
                else
                {
                    System.Data.DataSet oDataSet = new System.Data.DataSet();
                    oDataSet.ReadXmlSchema(strSchemaXml);
                    oDataSet.ReadXml(strTableXml);

                    if (oDataSet.Tables.Count > 0)
                    {
                        using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(oTargetDatabase.ConnectionString))
                        {
                            conn.Open();
                            System.Data.SqlClient.SqlTransaction oTran = conn.BeginTransaction();

                            System.Data.SqlClient.SqlBulkCopy oSqlBulkCopy
                                = new System.Data.SqlClient.SqlBulkCopy(conn, System.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity, oTran);
                            //= new System.Data.SqlClient.SqlBulkCopy(conn);
                            oSqlBulkCopy.BulkCopyTimeout = 600; // number of seconds
                            oSqlBulkCopy.BatchSize = 1000;
                            oSqlBulkCopy.DestinationTableName = strFullyQualifiedTableName; //"[" + strTableName + "]";
                            oSqlBulkCopy.NotifyAfter = 10000;
                            oSqlBulkCopy.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(oSqlBulkCopy_SqlRowsCopied);
                            foreach (System.Data.DataColumn ocol in oDataSet.Tables[0].Columns)
                            {
                                //System.Console.WriteLine(ocol.ColumnName);
                                oSqlBulkCopy.ColumnMappings.Add(ocol.ColumnName, ocol.ColumnName);
                            }

                            oSqlBulkCopy.WriteToServer(oDataSet.Tables[0]);
                            oTran.Commit();
                            conn.Close();
                        }
                        System.Console.WriteLine("Wrote : " + oDataSet.Tables[0].Rows.Count.ToString() + " records ");
                    }
                    else
                    {
                        System.Console.WriteLine("Wrote : 0 records ");
                    }

                    //using (System.Data.Sql)

                }
            
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        }

        static void oSqlBulkCopy_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
        {
            System.Console.WriteLine("Rows loaded : " + e.RowsCopied.ToString());
        }
    }
}
